#include <QDebug>
#include <QtGui/QApplication>
#include <QTranslator>
#include <QDir>
#include <QLibraryInfo>
#include "mainwindow.h"

#define APPNAME "kintai"

/**
* get translation path
*/
QString getTranslationPath(){
    QString appPath = qApp->applicationDirPath();
    QStringList pathList;

#ifdef Q_WS_WIN
    pathList << appPath + "/translations";
#elif defined(Q_WS_X11)
    pathList << appPath + "/translations"
             << "/usr/share/" APPNAME "/translations"
             << "/usr/local/share/" APPNAME "/translations";
#elif defined(Q_WS_MAC)
    pathList << QFileInfo(appPath + "/../Resources/translations/").absolutePath()
             << "./translations";
#endif

    foreach( const QString& path, pathList){
        if ( QDir(path).exists() ) {
            qDebug() << "translation path: " << path;
            return path;
        }
    }

    return "./";
}

/**
* install translator
*/
bool installTranslator(const QString& path, QString file){
    QTranslator* translator = new QTranslator;

    if (translator->load(file, path) == false){
        file = file.toLower();
        if (translator->load(file, path) == false) {
            delete translator;
            return false;
        }
    }
    QCoreApplication::installTranslator(translator);
    return true;
}

int main(int argc, char *argv[])
{
    QApplication::addLibraryPath("./plugins");
    QApplication::setOrganizationName("Rococo");
    QApplication::setOrganizationDomain("rococo.co.jp");
    QApplication::setApplicationName("nippou");
    QApplication::setApplicationVersion("1.0.4");

    QApplication a(argc, argv);

    QString locale = QLocale::system().name();
    qDebug() << "locale: " << locale;

    // application's translation path
    QString translationPath = getTranslationPath();

    // install qt translation file
    if (installTranslator(QLibraryInfo::location(QLibraryInfo::TranslationsPath), "qt_" + locale) == false)
        installTranslator(translationPath, "qt_" + locale);

    // install application translation file
    installTranslator(translationPath, "kintai_" + locale);

    // add plugin path
    a.addLibraryPath("./plugins");

    MainWindow w;
    w.show();

    return a.exec();
}
